//
//  UpdatePropertyDataModel.m
//  DataBind
//
//  Created by Super on 2019/12/20.
//  Copyright © 2019 Super. All rights reserved.
//

#import "UpdatePropertyDataModel.h"
#import <objc/runtime.h>

@implementation UpdatePropertyDataModel

+ (void)updateValueWith:(id)object key:(NSString *)key value:(id)value {
    NSString *propKey = [NSString stringWithFormat:@"_%@", key];
    
    unsigned  int count = 0;
    Ivar *members = class_copyIvarList([object class], &count);
    
    int index = -1;
    NSString *type = @"";
    
    for (int i = 0; i < count; i++) {
        Ivar var = members[i];
        const char *memberAddress = ivar_getName(var);
        const char *memberType = ivar_getTypeEncoding(var);
        NSString *address = [NSString stringWithFormat:@"%s", memberAddress];
        if ([propKey isEqualToString:address]) {
            index = i;
            type = [NSString stringWithFormat:@"%s", memberType];
            break;
        }
//        NSLog(@"address = %s ; type = %s", memberAddress, memberType);
    }
    if (index < 0) {
        NSLog(@"警告！！ %s类中不存在名为%@的属性", object_getClassName(object), key);
    } else {
        //对私有变量的更改
        Ivar m_address = members[index];
        
        if ([type hasPrefix:@"@"]) {
            //属性为对象
            object_setIvar(object, m_address, value);
        } else {
            //属性为基础类型
            [object setValue:value forKey:propKey];
        }
    }
}

@end
